package org.lanyu.springainovel.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类，用于生成和验证令�? */
@Component
public class JwtTokenUtil {

    @Value("${spring.jwt.secret}")
    private String jwtSecret;

    @Value("${spring.jwt.expiration}")
    private long jwtExpirationMs; // 修改为long类型以支持30天的毫秒数

    /**
     * 从令牌中获取用户�?     */
    public String getUsernameFromToken(String token) {
        try {
            Claims claims = parseToken(token);
            return claims.getSubject();
        } catch (Exception e) {
            System.err.println("Failed to get username from token: " + e.getMessage());
            return null;
        }
    }

    /**
     * 从令牌中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        try {
            Claims claims = parseToken(token);
            Object userIdObj = claims.get("userId");
            if (userIdObj instanceof Integer) {
                return ((Integer) userIdObj).longValue();
            } else if (userIdObj instanceof Long) {
                return (Long) userIdObj;
            } else if (userIdObj instanceof String) {
                return Long.parseLong((String) userIdObj);
            }
            return null;
        } catch (Exception e) {
            System.err.println("Failed to get userId from token: " + e.getMessage());
            return null;
        }
    }

    /**
     * 从令牌中获取用户昵称
     */
    public String getNicknameFromToken(String token) {
        try {
            Claims claims = parseToken(token);
            return (String) claims.get("nickname");
        } catch (Exception e) {
            System.err.println("Failed to get nickname from token: " + e.getMessage());
            return null;
        }
    }

    /**
     * 从令牌中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        try {
            Claims claims = parseToken(token);
            return claims.getExpiration();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解析令牌 - 使用JJWT 0.9.1版本的API
     */
    private Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(jwtSecret.getBytes())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JWT token", e);
        }
    }

    /**
     * 检查令牌是否过�?     */
    private Boolean isTokenExpired(String token) {
        Date expiration = getExpirationDateFromToken(token);
        return expiration != null && expiration.before(new Date());
    }

    /**
     * 生成令牌
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return createToken(claims, userDetails.getUsername());
    }

    /**
     * 生成包含用户ID的令�?     */
    public String generateTokenWithUserId(UserDetails userDetails, Long userId, String nickname) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        if (nickname != null) {
            claims.put("nickname", nickname);
        }
        return createToken(claims, userDetails.getUsername());
    }

    /**
     * 创建令牌 - 使用JJWT 0.9.1版本的API
     */
    private String createToken(Map<String, Object> claims, String subject) {
        try {
            return Jwts.builder()
                    .setClaims(claims)
                    .setSubject(subject)
                    .setIssuedAt(new Date(System.currentTimeMillis()))
                    .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationMs))
                    .signWith(SignatureAlgorithm.HS512, jwtSecret.getBytes())
                    .compact();
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate JWT token", e);
        }
    }

    /**
     * 验证令牌
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        try {
            final String username = getUsernameFromToken(token);
            boolean isValid = username != null && username.equals(userDetails.getUsername()) && !isTokenExpired(token);
            if (!isValid) {
                System.err.println("Token validation failed. Username match: " + (username != null && username.equals(userDetails.getUsername())) + 
                                  ", Token expired: " + isTokenExpired(token));
            }
            return isValid;
        } catch (Exception e) {
            System.err.println("Token validation exception: " + e.getMessage());
            return false;
        }
    }
}
